package com.phelon.epdm;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.BooleanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.phelon.systemLink.SessionInfo;
import com.phelon.systemLink.SessionManager;

public class BillOfMaterialComponentXMLBuilder {
	
	private String 						environmentID;
	private Document 					document;
	private Document					responseDocument;
	private BillOfMaterialComponent 	theBomDetail;
	private List<String>				errorMessages;
	
	public static void main(String[] args) {
		BillOfMaterial testBom = new BillOfMaterial("A  ", "ASP9802536  ", "      ");
		BillOfMaterialComponentXMLBuilder builder = new BillOfMaterialComponentXMLBuilder(testBom, "7M");
		builder.doCreateBomDetail();
		System.exit(0);
			}
	public BillOfMaterialComponentXMLBuilder(BillOfMaterial theBomHeader, String toEnv) {
		this.theBomDetail = theBomDetail;
		this.environmentID = toEnv;
	}
	
	public void doCreateBomDetail() {
		SessionManager sm = SessionManager.getInstance();
        SessionInfo session = sm.getSessionInfo(this.environmentID);
        buildBomComponentXML(session);
        /* post xml */
        String xmlFile = "c:/temp/xml/document.xml";
        serializeXML(xmlFile);
        String response = sm.postXML(document.asXML());
        try {
			boolean success = readResponse(response);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        /* check for success or errors */

        /* notify or update */
    }

// TODO Auto-generated method stub
		

	public boolean readResponse(String response) throws DocumentException {
        responseDocument = DocumentHelper.parseText(response);

        XPath xpathSelector = DocumentHelper.createXPath("//CreateResponse");
        List<Element> results = xpathSelector.selectNodes(responseDocument);
        boolean success = true;
        String Item = responseDocument
                .valueOf("//CreateResponse[@name='newItem']/Key/Property[@path='vendor']/Value");
        for (Element e : results) {
            String objectName = e.attributeValue("name");
            if (BooleanUtils.toBoolean(e.attributeValue("actionSucceeded"))) {
                System.out.println("Action succeeded for item '" + objectName + "'");
            } else {
                System.out.println("Action was not successful for item '" + objectName + "'");
                success = false;
            }
        }
        if (success == false) {
        	errorMessages = new ArrayList<String>();
        	XPath xpathSelector2 = DocumentHelper.createXPath
        	 		("//CreateResponse/Exception/Message/Text");
            List<Element> results2 = xpathSelector2.selectNodes(responseDocument);
            for (Element e2 : results2) {
                 errorMessages.add(e2.getText());
             }	
        	
        }
        return success;
    }
	
	private void buildBomComponentXML(SessionInfo theSession) {
		document = DocumentHelper.createDocument();
		
		document.addDocType("System-Link", "SYSTEM", "SystemLinkRequest.dtd");
		
		Element root = document.addElement("System-Link").addAttribute("formatForDisplay", "true");
		
		Element request = root.addElement("Request").addAttribute("sessionHandle"
				,theSession == null ? "*current" : theSession.getSessionHandle()).addAttribute(
				"workHandle", "*new").addAttribute("broker","EJB").addAttribute("maxIdle", "1000");
		Element domainEntity = request.addElement("Create").addAttribute("name",
				"queryObject_ItemRevision_Default").addAttribute("domainClass","com.mapics.epdm.ItemRevision")
				.addAttribute("retainResult", "true").addElement("DomainEntity");
		Element key = domainEntity.addElement("Key");
		key.addElement("Property").addAttribute("path", "site").addElement("Value")
				.addCDATA(theBomDetail.getSite());
        key.addElement("Property").addAttribute("path", "parentItem").addElement("Value")
        		.addCDATA(theBomDetail.getParentItem());
        key.addElement("Property").addAttribute("path", "parentItemRevision").addElement("Value")
        		.addCDATA(theBomDetail.getParentItemRevision());;  
/*        domainEntity.addElement("Property").addAttribute("path", "apcItem").addElement("Value").addCDATA(
        		theItem.getApcItem()); */
        domainEntity.addElement("Property").addAttribute("path", "alternativeBomId").addElement("Value").addCDATA(
                theBomDetail.getAlternativeBomId());
        domainEntity.addElement("Property").addAttribute("path", "componentConfigurationId").addElement("Value").addCDATA(
                theBomDetail.getComponentConfigurationId());
        domainEntity.addElement("Property").addAttribute("path", "componentLeadTimeAdjustment").addElement("Value").addCDATA(
                theBomDetail.getComponentLeadTimeAdjustment());
        domainEntity.addElement("Property").addAttribute("path", "effectiveFromDate").addElement("Value").addCDATA(
                theBomDetail.getEffectiveFromDate());
        domainEntity.addElement("Property").addAttribute("path", "effectiveToDate").addElement("Value").addCDATA(
                theBomDetail.getEffectiveToDate());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionCode").addElement("Value").addCDATA(
                theBomDetail.getFeatureOptionCode());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionCostRollUpFactor").addElement("Value").addCDATA(
                theBomDetail.getFeatureOptionCostRollUpFactor());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getFeatureOptionNumber());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getFeatureOptionPlanningFactor());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getOperationWhereFirstUsed());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getQuantityPerUnit());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getUserFieldCodeA());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getUserFieldDate1());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getUserFieldQuantity1());
        domainEntity.addElement("Property").addAttribute("path", "featureOptionNumber").addElement("Value").addCDATA(
                theBomDetail.getUserFieldQuantity2());

        
 	}

	private void serializeXML(String xmlFile) {
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("ISO-8859-1");
        OutputStream out;
        try {
            out = FileUtils.openOutputStream(new File(xmlFile));
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(document);
            writer.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	public List<String> getErrorMessages() {
		return errorMessages;
	}  
}

	